package org.dg.iag.server;

import java.util.HashMap;
import java.util.Map.Entry;

import org.dg.iag.dao.GenericDAO;
import org.dg.iag.query.XQueryGet;
import org.dg.iag.util.ApplicationConstants;
import org.dg.iag.util.HardCodedIatiInfo;
import org.dg.iag.util.RestletUtil;
import org.restlet.resource.Get;
import org.restlet.resource.ServerResource;

public class EntityListServerResource extends ServerResource {
	@Get
	public Object getEntityList() {
		
		String entity					= RestletUtil.getPathFromRequest(getRequest(), "entityName");
		
		HashMap<String, String> params	= new HashMap<String, String>();
		RestletUtil.populateParamsMap(params, getRequest());

		GenericDAO<Object, Object> gdao			= new GenericDAO<Object, Object>(ApplicationConstants.IATI_STORAGE_PATH);
		String format					= params.remove("format");
		
		XQueryGet xqg;
		if ( entity != null) {
			if ( params.size() == 0 ) {
				if ( HardCodedIatiInfo.entityToId.containsKey(entity) ) {
					gdao			= new GenericDAO<Object, Object>(ApplicationConstants.CACHE_PATH + "/");
					xqg				= new XQueryGet(entity.replace("/", "_") + ".xml", "/results/item", true);
				}
				else
					xqg					= new XQueryGet("", 
						"(for $item in distinct-values(/iati-activities/iati-activity"+entity+") " +
								"order by $item return <item>{$item}</item>)", 
						true);
			}
			else {
				Entry<String, String> e1		= params.entrySet().iterator().next();
				//XQueryGet xqg					= new XQueryGet("", "/iati-activities/iati-activity[iati-identifier='"+params.get("iati-identifier")+"']", false);
				if ( e1.getKey().startsWith("/") ) {
					xqg					= new XQueryGet("", 
							"(for $item in distinct-values(/iati-activities/iati-activity[."+e1.getKey()+"='"+e1.getValue()+"']"+entity+") " +
									"order by $item return <item>{$item}</item>)", 
							true);
				}
				else
					//TODO ugly, needs to be changed
					if ( "@role".equals(e1.getKey()) && "Funding".equals(e1.getValue()) && "/participating-org".equals(entity) ){
						gdao			= new GenericDAO<Object, Object>(ApplicationConstants.CACHE_PATH + "/");
						xqg				= new XQueryGet(entity.replace("/", "_") + ".xml", "/results/item", true);
					}
					else
						xqg					= new XQueryGet("", 
								"(for $item in distinct-values(/iati-activities/iati-activity"+entity+"["+e1.getKey()+"='"+e1.getValue()+"']) " +
										"order by $item return <item>{$item}</item>)", 
								true);
			}
			
			String start 	= (String)this.getRequest().getAttributes().get("start");
			if (start != null) {
				try {
					xqg.setStart(Integer.parseInt(start));
				} catch (NumberFormatException e) {
					e.printStackTrace();
				}
			}
			String howmany 	= (String)this.getRequest().getAttributes().get("howmany");
			if (howmany != null) {
				try {
					xqg.setHowmany(Integer.parseInt(howmany));
				} catch (NumberFormatException e) {
					e.printStackTrace();
				}
			}
			String ret						= gdao.getElementsAsString(xqg);
//			StringBuilder sb				= new StringBuilder( 2*"</results>".length() + ret.length() );
//			sb.append("<results>").append(ret).append("</results>");
//			ret								= sb.toString();
			if (format != null && "json".equals( format ) ) {
				ret		= RestletUtil.generateJsonFromXML(ret);
			}
			
			
			return ret;
		}
		return "Nothing found";
	}
}
